package per.sen.shopping.infrastructure.consul;

import io.quarkus.runtime.StartupEvent;
import io.vertx.ext.consul.CheckOptions;
import io.vertx.ext.consul.CheckStatus;
import io.vertx.ext.consul.ConsulClientOptions;
import io.vertx.ext.consul.ServiceOptions;
import io.vertx.mutiny.core.Vertx;
import io.vertx.mutiny.ext.consul.ConsulClient;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import org.eclipse.microprofile.config.inject.ConfigProperty;


/**
 * @Descibe: 注册服务consul
 * @Author: LYS
 * @Date: 2024/4/26 17:24
 */

@ApplicationScoped
public class Registration {
    @ConfigProperty(name="quarkus.application.name")
    String applicationName;

    @ConfigProperty(name = "quarkus.stork.shopping-manager.service-discovery.consul-host")
    String host;
    @ConfigProperty(name = "quarkus.stork.shopping-manager.service-discovery.consul-port")
    int port;
    @ConfigProperty(name = "quarkus.http.port")
    int servicePort;
    @ConfigProperty(name = "quarkus.http.host")
    String serviceHost;

    public void init(@Observes StartupEvent ev, Vertx vertx) {
        CheckOptions checkOptions = new CheckOptions();
        checkOptions.setInterval("30s");
        checkOptions.setStatus(CheckStatus.PASSING);

        checkOptions.setHttp("http://"+ serviceHost + ":" + servicePort + "/q/health/live");
        ConsulClientOptions consulClientOptions = new ConsulClientOptions().setHost(host).setPort(port);

        ConsulClient client = ConsulClient.create(vertx, consulClientOptions);

        try {
        client.registerServiceAndAwait(
                new ServiceOptions().
                        setPort(servicePort).
                        setAddress(serviceHost).
                        setName(applicationName).
                        setCheckOptions(checkOptions));
    } catch (Throwable throwable){
            client.close();
            throw new RuntimeException(throwable.getMessage());
        }
    }








}
